<!--

-->
<template>
    <div class="GImageListUpload">
        <div v-for="item in list" :key="item.id" class="preview">
            <img :src="imageFullPath(item.path)" class="image"/>
            <div class="cover">
                <div class="btn" @click="show(item)">查看</div>
                <div class="btn delete" @click="remove(item)">移除</div>
            </div>
        </div>
        <div v-if="list.length < max" class="placeholder" @click="choose">
            <b-icon name="bi-cloud-arrow-up" size="26"/>
        </div>
    </div>
</template>

<script>
import * as uuid from "uuid";
import * as api from "./api.js"
export default {
    name: "GImageListUpload",
    emits: ["update:modelValue"],
    props: {
        modelValue: {
            type: String,
            default: () => ""
        },
        params: {
            type: Object,
            default: () => {
            }
        },
        max: {
            type: Number,
            default: () => 6
        }
    },
    data() {
        return {
            list: []
        }
    },
    watch: {
        modelValue() {
            this.setListValue()
        }
    },
    mounted() {
        this.setListValue();
    },
    methods: {
        setListValue() {
            if (this.modelValue) {
                const list = this.modelValue.split(";").filter(item => item).map(item => {
                    return {
                        path: item,
                        id: item
                    }
                })
                this.list = list;
            } else {
                this.list = [];
            }
        },
        imageFullPath(val) {
            const host = window.$config.baseUrl;
            return host + "/" + val;
        },
        checkFileType({name}, type) {
            if (type === "*") return true;
            const arr = name.split(".");
            const fileType = ("." + arr[arr.length - 1]).toLowerCase();
            const fileTrue = type.indexOf(fileType) > -1;
            if (!fileTrue) {
                $message.error(`文件类型错误，请使用 ${type} 类型的文件`);
            } else {
                return true;
            }
        },
        show(item) {
            this.showBig(this.imageFullPath(item.path));
        },
        showBig(fullPath) {
            const width = 500;
            const height = 600;
            const left = (document.documentElement.clientWidth - width) / 2;
            window.open(fullPath, "", `width=${width}, height=${height}, left=${height}, top=160`)
        },
        remove(item) {
            const index = this.list.findIndex(t => t.id === item.id);
            this.list.splice(index, 1);
            const modelValue = this.list.map(t => t.path).join(";");
            this.$emit("update:modelValue", modelValue)
        },
        startUpload(file) {
            const formData = new FormData();
            formData.append("fileList", file);
            return api.upload(this.params, formData)
        },
        async uploadAll(files, callback) {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (this.checkFileType(file, ".jpg|.jpeg|.png|.gif")) {
                    const {success, data} = await this.startUpload(file);
                    if (success) {
                        $message.success(file.name + " 上传成功")
                        const list = this.modelValue ? this.modelValue.split(";").filter(item => item) : [];
                        list.push(data)
                        const modelValue = list.join(";");
                        this.$emit("update:modelValue", modelValue)
                    } else {
                        $message.error(file.name + " 上传失败")
                    }
                    callback&&callback()
                }
            }
        },
        choose() {
            $chooseFile({
                count: this.max - this.list.length,
                extension: ['.jpeg', '.jpg', '.png'],
                maxSize: 5000,
                zipSize: 2000,
                success: (files) => {
                    this.uploadAll(files)
                }
            })
        },
        upload() {
            const form = document.createElement("form");
            const input = document.createElement("input");
            const id = "tempform_" + uuid.v4();
            form.id = id;
            form.enctype = "multipart/form-data";
            input.name = "fileList";
            input.multiple = "multiple";
            input.accept = "image/png,image/gif,image/jpeg"
            input.type = "file";
            input.style.width = "10px";
            input.style.height = "10px";
            input.style.opacity = "0.1";
            form.appendChild(input);
            document.body.appendChild(form);
            input.onchange = () => {
                setTimeout(() => {
                    let files = [];
                    const count = this.max - this.list.length;
                    if (input.files.length > count) {
                        $message.warn(`本次最大允许上传 ${count} 张图片`);
                        for (let i = 0; i < input.files.length; i++) {
                            files.push(input.files[i])
                        }
                        files = files.slice(0, count)
                    } else {
                        files = input.files;
                    }
                    this.uploadAll(files, success => {
                        form.remove();
                    });
                }, 300);

            };
            input.click();
        },
    }
}
</script>

<style lang="scss" scoped>
.GImageListUpload {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: wrap;
    .preview {
        width: 100px;
        height: 100px;
        border-radius: 6px;
        border: 1px solid #dcdfe6;
        margin-right: 10px;
        margin-bottom: 10px;
        position: relative;
        overflow: hidden;

        .image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .cover {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 10;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            background: rgba(0, 0, 0, 0);
            opacity: 0;
            .btn {
                font-size: 14px;
                color: var(--el-color-primary);
                width: 40px;
                height: 30px;
                display: flex;
                flex-direction: row;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                &:active {
                    opacity: 0.8;
                }
            }

            .delete {
                color: var(--el-color-danger);
            }
        }

        &:hover {
            .cover {
                opacity: 1;
                background: rgba(0, 0, 0, 0.5);
            }
        }
    }

    .placeholder {
        width: 100px;
        height: 100px;
        border-radius: 6px;
        border: 1px dashed #dcdfe6;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        color: #999;
        cursor: pointer;

        &:hover {
            border: 1px dashed var(--el-color-primary);
            color: var(--el-color-primary);
        }

        &:active {
            border: 1px dashed var(--el-color-primary);
            color: var(--el-color-primary);
            opacity: 0.8;
        }
    }
}
</style>
